package com.youmingxing.activity.selfInfo;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.tencent.upload.task.ITask;
import com.tencent.upload.task.IUploadTaskListener;
import com.tencent.upload.task.data.FileInfo;
import com.youmingxing.R;
import com.youmingxing.activity.BaseActivity;
import com.youmingxing.bean.User;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.SelfInfoApi;
import com.youmingxing.network.TXYUploadManager;
import com.youmingxing.utils.TimeUtils;
import com.youmingxing.utils.Util;
import com.youmingxing.view.DialogManager;
import com.youmingxing.view.MyDatePickerDialog;

import org.json.JSONObject;

import java.io.File;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

/**
 * @author evilyin(ChenZhixi)
 * @since 2015-10-9
 */

public class ModifyInfoActivity extends BaseActivity {

    ListView modifyList;

    private static final int HEAD_IMG = 1;
    private static final int CROP_HEAD_IMG = 5;
    private static final int EDIT_TEXT = 2;
    private static final int CHOOSE_ADDRESS = 3;
    private static final int BODY = 4;

    private String[] userData;

    ModifyAdapter adapter = new ModifyAdapter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_modify_info);
        setTopbarName("编辑资料");
        modifyList = (ListView) findViewById(R.id.modify_info_list);
        //从上级页面获取userdata
        userData = getIntent().getExtras().getStringArray("userData");

        modifyList.setAdapter(adapter);
        modifyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (User.Info.values()[position]) {
                    case headimg:
                        PhotoPickerIntent intentPP = new PhotoPickerIntent(ModifyInfoActivity.this);
                        intentPP.setPhotoCount(1);
                        intentPP.setShowCamera(true);
                        intentPP.setShowGif(false);
                        startActivityForResult(intentPP, HEAD_IMG);
                        break;
                    case nickname:
                    case motto:
                    case career_or_college:
                    case link_mobile:
                    case link_email:
                        Intent intent = new Intent(ModifyInfoActivity.this, EditTextActivity.class);
                        intent.putExtra("option", position);
                        intent.putExtra("text", userData[position]);
                        startActivityForResult(intent, EDIT_TEXT);
                        break;
                    case gender:
                        AlertDialog.Builder builder = new AlertDialog.Builder(ModifyInfoActivity.this);
                        final String[] sex = {"男", "女"};
                        builder.setItems(sex, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SelfInfoApi.modifyUserProfile("gender", which + 1 + "", jsonHandler);
                                userData[User.Info.gender.ordinal()] = sex[which];
                            }
                        });
                        builder.show();
                        break;
                    case birthday:
                        int[] defaultDate = TimeUtils.parseBirthday(userData[User.Info.birthday
                                .ordinal()]);
                        MyDatePickerDialog dpDialog = new MyDatePickerDialog(ModifyInfoActivity.this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                String date = year + "." + (monthOfYear + 1) + "." + dayOfMonth;
                                SelfInfoApi.modifyUserProfile("birthday", date, jsonHandler);
                                userData[User.Info.birthday.ordinal()] = date;
                            }
                        }, defaultDate[0], defaultDate[1]-1, defaultDate[2]);
                        dpDialog.show();
                        break;
                    case body:
                        Intent bodyIntent = new Intent(ModifyInfoActivity.this, ModifyBodyActivity.class);
                        bodyIntent.putExtra("text", userData[position]);
                        startActivityForResult(bodyIntent, BODY);
                        break;
                    case address:
                    case hometown:
                        Intent intent1 = new Intent(ModifyInfoActivity.this, ModifyAddressActivity.class);
                        intent1.putExtra("option", position);
                        startActivityForResult(intent1, CHOOSE_ADDRESS);
                        break;

                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case HEAD_IMG:
                    String photoPath = data.getStringArrayListExtra(PhotoPickerActivity
                            .KEY_SELECTED_PHOTOS).get(0);
                    File file = new File(photoPath);
                    Uri mUri = Uri.fromFile(file);
                    if (null == mUri) return;
                    Intent intent = new Intent();
                    intent.setAction("com.android.camera.action.CROP");
                    intent.setDataAndType(mUri, "image/*");// mUri是已经选择的图片Uri
                    intent.putExtra("crop", "true");
                    intent.putExtra("aspectX", 1);// 裁剪框比例
                    intent.putExtra("aspectY", 1);
                    intent.putExtra("outputX", 300);// 输出图片大小
                    intent.putExtra("outputY", 300);
                    intent.putExtra("return-data", true);
                    ModifyInfoActivity.this.startActivityForResult(intent, CROP_HEAD_IMG);
                    break;
                case CROP_HEAD_IMG:
                    // 拿到剪切数据
                    DialogManager.showDialog(ModifyInfoActivity.this, "上传中");
                    Bitmap bmap = data.getParcelableExtra("data");
                    byte[] img = Util.Bitmap2Bytes(Util.compressImage(bmap));
                    bmap.recycle();
                    TXYUploadManager.uploadPhoto(img, new
                            IUploadTaskListener() {
                                @Override
                                public void onUploadSucceed(FileInfo fileInfo) {
                                    SelfInfoApi.modifyUserProfile("headimg", fileInfo.url, jsonHandler);
                                    userData[User.Info.headimg.ordinal()] = fileInfo.url;
                                    Toast.makeText(ModifyInfoActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onUploadFailed(int i, String s) {
                                    Toast.makeText(ModifyInfoActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onUploadProgress(long l, long l1) {

                                }

                                @Override
                                public void onUploadStateChange(ITask.TaskState taskState) {

                                }
                            });
                    break;
                case EDIT_TEXT:
                    int index = data.getExtras().getInt("option");
                    String value = data.getExtras().getString("value");
                    userData[index] = value;
                    break;
                case CHOOSE_ADDRESS:
                    int index1 = data.getExtras().getInt("option");
                    String address = data.getExtras().getString("address");
                    userData[index1] = address;
                    break;
                case BODY:
                    String body = data.getExtras().getString("body");
                    userData[User.Info.body.ordinal()] = body;
                    break;

            }
            adapter.notifyDataSetChanged();
        }
    }

    JsonHttpResponseHandler jsonHandler = new BaseJsonHandler(this) {

        @Override
        public void onSuccessWithData(JSONObject response) {
            if (response.optJSONObject("data").optInt("result") == 1) {
//                showToast("修改成功");
            }
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onFail(int statusCode, String statusText) {
            showToast("修改失败");
        }

    };


    @Override
    public void finish() {

        //把userData传回去
        Intent intent = new Intent();
        intent.putExtra("userData", userData);
        setResult(RESULT_OK, intent);
        super.finish();
    }


    private static class ViewHolder {
        ImageView headImage;
        TextView optionText;
        TextView optionValueText;
        View divider;
    }

    private class ModifyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return User.Info.values().length - 1;
        }

        @Override
        public Object getItem(int position) {
            return User.Info.values()[position].getDesc();
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public android.view.View getView(int position, View convertView, ViewGroup parent) {
            if (position < User.Info.link_mobile.ordinal()) {
                //前半部分
                ViewHolder holder = new ViewHolder();
                convertView = View.inflate(ModifyInfoActivity.this, R.layout.list_item_modify_info, null);
                holder.headImage = (ImageView) convertView.findViewById(R.id.image_avatar);
                holder.optionText = (TextView) convertView.findViewById(R.id.option_text);
                holder.optionValueText = (TextView) convertView.findViewById(R.id.option_value_text);
                holder.optionText.setText(User.Info.values()[position].getDesc());
                if (position == 0) {
                    Glide.with(ModifyInfoActivity.this).load(userData[0])
                            .placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar)
                            .bitmapTransform(new CropCircleTransformation(
                                    ModifyInfoActivity.this)).crossFade().into
                            (holder.headImage);
                    holder.optionValueText.setVisibility(View.GONE);
                } else {
                    holder.headImage.setVisibility(View.GONE);
                }
                String realString = userData[position];
                if (realString.contains(" 0cm")) {
                    realString = realString.replace(" 0cm", "");
                }
                if (realString.contains(" 0kg")) {
                    realString = realString.replace(" 0kg", "");
                }
                if (realString.contains("0,0,0")) {
                    realString = realString.replace("0,0,0", "");
                }
                if (realString.isEmpty()||realString.equals(" ")) {
                    holder.optionValueText.setText("未填写");
                } else {
                    holder.optionValueText.setText(realString);
                }
            } else {
                //后半部分
                ViewHolder holder = new ViewHolder();
                convertView = View.inflate(ModifyInfoActivity.this, R.layout.footer_modify_info, null);
                holder.optionText = (TextView) convertView.findViewById(R.id.footer_option_text);
                holder.optionValueText = (TextView) convertView.findViewById(R.id.footer_option_value);
                holder.divider = convertView.findViewById(R.id.divider);
                holder.optionText.setText(User.Info.values()[position].getDesc());

                if (position == User.Info.link_mobile.ordinal()) {
                    holder.divider.setVisibility(View.VISIBLE);
                } else {
                    holder.divider.setVisibility(View.GONE);
                }
                if (userData[position].equals("")) {
                    holder.optionValueText.setText("未填写");
                } else {
                    holder.optionValueText.setText(userData[position]);
                }
            }
            return convertView;
        }
    }
}
